package com.btl.cygf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.btl.bean.Person;
import com.btl.http.HttpServies;
import com.btl.utils.MD5Encrypt;
import com.btl.utils.RoundImag;
import com.btl.utils.SavaPersonInfo;
import com.btl.zujian.SelectPicPopup;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.yzx.yunyanzhengdemo.activity.LoginActivity;

public class PersonInfo extends Activity implements OnClickListener {
	private EditText nicheng;
	private EditText qianming;
	private ImageView My_head;
	private ImageView login_backtofragment;
	private TextView zhanghao;
	private TextView shouji;
	private Button baocun1;
	private Button baocun2;
	private LinearLayout shouji_layout, qiehuan_zhanghao, xiugai_pass;

	private SelectPicPopup spp;

	private static String path = "/sdcard/btl/";// sd路径
	private Bitmap head;

	private Bitmap pic;
	private Person p;

	private boolean value;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0x1123) {
				
				if(!(pic == null)) {
					My_head.setImageBitmap(RoundImag.toRoundBitmap(getApplicationContext(), pic));
				}
			}

			if (msg.what == 0x1124) {
				SavaPersonInfo.saveInfo(getApplicationContext(), p);
				Intent it = new Intent(PersonInfo.this, MainActivity.class);
				it.putExtra("type", 1);
				it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(it);

			}

			if (msg.what == 0x1125) {
				if (value) {
					Toast.makeText(getApplicationContext(), "修改成功", 1).show();
				} else {
					Toast.makeText(getApplicationContext(), "修改失败", 1).show();
				}
			}

		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.person_info);

		initView();

	}

	private void initView() {
		nicheng = (EditText) findViewById(R.id.nicheng);
		qianming = (EditText) findViewById(R.id.qianming);
		My_head = (ImageView) findViewById(R.id.My_head);
		login_backtofragment = (ImageView) findViewById(R.id.login_backtofragment);
		zhanghao = (TextView) findViewById(R.id.zhanghao);
		shouji = (TextView) findViewById(R.id.shouji);
		baocun1 = (Button) findViewById(R.id.baocun1);
		baocun2 = (Button) findViewById(R.id.baocun2);
		shouji_layout = (LinearLayout) findViewById(R.id.shouji_layout);
		qiehuan_zhanghao = (LinearLayout) findViewById(R.id.qiehuan_zhanghao);
		xiugai_pass = (LinearLayout) findViewById(R.id.xiugai_pass);

		My_head.setFocusable(true);
		My_head.setFocusableInTouchMode(true);
		My_head.requestFocus(); // 初始不让EditText得焦点
		My_head.requestFocusFromTouch();
		baocun1.setOnClickListener(this);
		baocun2.setOnClickListener(this);
		shouji_layout.setOnClickListener(this);
		qiehuan_zhanghao.setOnClickListener(this);
		xiugai_pass.setOnClickListener(this);
		My_head.setOnClickListener(this);
		login_backtofragment.setOnClickListener(this);

		final SharedPreferences share = getSharedPreferences("login",
				Activity.MODE_WORLD_READABLE);

		zhanghao.setText(share.getString("id", ""));
		nicheng.setText(share.getString("nickname", ""));
		qianming.setText(share.getString("intro", ""));
		final String avatar = share.getString("avatar", "");

		new Thread(new Runnable() {
			@Override
			public void run() {

				try {
					pic = HttpServies.getBitmap(avatar);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				handler.sendEmptyMessage(0x1123);
			}
		}).start();

		String phone = share.getString("phone", "");
		if (phone.equals("")) {
			shouji_layout.setVisibility(View.GONE);
		} else {
			shouji.setText(phone);
		}
		String pass = share.getString("pass", "");
		System.out.println(pass);
		if (share.getString("id", "").length() > 11) {
			xiugai_pass.setVisibility(View.GONE);
		}

		nicheng.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				baocun1.setVisibility(View.VISIBLE);

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (nicheng.getText().toString()
						.equals(share.getString("nickname", ""))) {
					baocun1.setVisibility(View.GONE);
				}

			}
		});
		qianming.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				baocun2.setVisibility(View.VISIBLE);

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (qianming.getText().toString()
						.equals(share.getString("intro", ""))) {
					baocun2.setVisibility(View.GONE);
				}

			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.My_head:
			getImage();
			break;
		case R.id.login_backtofragment:
			updateLoginInfo();

			break;
		case R.id.baocun1:
			updatePersonInfo("nickname");
			baocun1.setVisibility(View.GONE);
			break;
		case R.id.baocun2:
			updatePersonInfo("intro");
			baocun2.setVisibility(View.GONE);
			break;
		case R.id.qiehuan_zhanghao:

			Intent it2 = new Intent(PersonInfo.this, LoginActivity.class);
			it2.putExtra("type", "2");

			startActivity(it2);

			break;
		case R.id.xiugai_pass:
			startActivity(new Intent(PersonInfo.this, UpdatePass.class));
			break;
		}

	}

	private void updatePersonInfo(final String type) {
		final SharedPreferences share = getSharedPreferences("login",
				Activity.MODE_WORLD_READABLE);
		final String id = share.getString("id", "");
		new Thread(new Runnable() {
			@Override
			public void run() {

				Map<String, String> params = new HashMap<>();
				params.put("id", id);
				if (type.equals("nickname")) {

					params.put("param", nicheng.getText().toString());
					params.put("type", "nickname");

				} else if (type.equals("intro")) {
					params.put("param", qianming.getText().toString());
					params.put("type", "intro");
				}

				try {
					value = (boolean) HttpServies.SendPostRequest(
							getResources().getString(R.string.url)
									+ "/CYGF/updatePerson.user", params,
							"utf-8", 1);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				handler.sendEmptyMessage(0x1125);
			}
		}).start();

	}

	private void updateLoginInfo() {
		SharedPreferences share = getSharedPreferences("login",
				Activity.MODE_WORLD_READABLE);

		final String id = share.getString("id", "");
		new Thread(new Runnable() {

			@Override
			public void run() {

				Map<String, String> params = new HashMap<>();
				params.put("id", id);

				try {
					p = (Person) HttpServies.SendPostRequest(getResources()
							.getString(R.string.url) + "/CYGF/login.user",
							params, "utf-8", 3);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				handler.sendEmptyMessage(0x1124);
			}
		}).start();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {

				updateLoginInfo();

			}
		}
		return false;
	}

	private void getImage() {

		spp = new SelectPicPopup(PersonInfo.this, itemsOnClick);
		spp.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM
				| Gravity.CENTER_HORIZONTAL, 0, 0);

	}

	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			spp.dismiss();
			switch (v.getId()) {
			case R.id.btn_take_photo:
				Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent2.putExtra(
						MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(new File(Environment
								.getExternalStorageDirectory(), "btl/head.jpg")));
				startActivityForResult(intent2, 2);// 采用ForResult打开

				break;
			case R.id.btn_pick_photo:
				Intent intent1 = new Intent(Intent.ACTION_PICK, null);
				intent1.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
				startActivityForResult(intent1, 1);

				break;
			default:
				break;
			}

		}

	};

	private void saveAvatar() {
		SharedPreferences share = getSharedPreferences("login",
				Activity.MODE_WORLD_READABLE);

		final String id = share.getString("id", "");
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("id", id);
		try {
			params.put("image", new File(path + "head.jpg"));
			client.post("http://10.202.1.42:8080/CYGF/updateAvatar.user",
					params, new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int arg0, Header[] arg1,
								byte[] arg2) {
							Toast.makeText(getApplicationContext(), "修改成功", 1)
									.show();
							My_head.setImageBitmap(RoundImag.toRoundBitmap(
									getApplicationContext(),
									BitmapFactory.decodeFile(path + "head.jpg")));

						}

						@Override
						public void onFailure(int arg0, Header[] arg1,
								byte[] arg2, Throwable arg3) {
							Toast.makeText(getApplicationContext(), "修改失败", 1)
									.show();

						}
					});
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 1:
			if (resultCode == -1) {
				cropPhoto(data.getData());// 裁剪图片
			}
			break;
		case 2:
			if (resultCode == -1) {
				File temp = new File(Environment.getExternalStorageDirectory()
						+ "/btl/head.jpg");
				cropPhoto(Uri.fromFile(temp));// 裁剪图片
			}
			break;
		case 3:
			if (data != null) {
				Bundle extras = data.getExtras();
				head = extras.getParcelable("data");
				if (head != null) {
					/**
					 * 上传服务器代码
					 */
					System.out.println(head);
					setPicToView(head);// 保存在SD卡中

				}
			}
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	};

	/**
	 * 调用系统的裁剪
	 * 
	 * @param uri
	 */
	public void cropPhoto(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	private void setPicToView(Bitmap mBitmap) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			return;
		}
		FileOutputStream b = null;
		File file = new File(path);
		file.mkdirs();// 创建文件夹
		String fileName = path + "head.jpg";// 图片名字
		try {
			b = new FileOutputStream(fileName);
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
			saveAvatar();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
